package com.example.backend.util;

import com.example.backend.domain.entity.User;
import com.example.backend.domain.enums.Role;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * 当前用户服务
 * 用于获取当前登录用户信息
 */
@Service
public class CurrentUserService {
    private static final Logger log = LoggerFactory.getLogger(CurrentUserService.class);
    
    /**
     * 获取当前登录用户
     * @return 当前用户，如果未登录则抛出异常
     * @throws RuntimeException 如果未找到当前登录用户
     */
    public User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        
        if (authentication != null && authentication.getPrincipal() instanceof User) {
            User user = (User) authentication.getPrincipal();
            log.info("[CurrentUserService] 获取当前用户: username={}, id={}, role={}, status={}",
                    user.getUsername(), user.getId(), user.getRole(), user.getStatus());
            return user;
        }
        
        log.error("[CurrentUserService] 未找到当前登录用户，调用栈：", new RuntimeException());
        throw new RuntimeException("未找到当前登录用户");
    }
    
    /**
     * 安全地获取当前用户（不抛异常）
     * @return 当前用户，如果未登录则返回null
     */
    public User getCurrentUserSafely() {
        try {
            User user = getCurrentUser();
            return user;
        } catch (Exception e) {
            log.warn("[CurrentUserService] getCurrentUserSafely 获取失败: {}", e.getMessage());
            return null;
        }
    }
    
    /**
     * 获取当前用户ID
     * @return 用户ID
     * @throws RuntimeException 如果未找到当前登录用户
     */
    public Long getCurrentUserId() {
        User user = getCurrentUser();
        if (user != null) {
            log.info("[CurrentUserService] 获取当前用户ID: {}", user.getId());
            return user.getId();
        } else {
            log.error("[CurrentUserService] getCurrentUserId: 当前用户为空");
            throw new RuntimeException("未找到当前登录用户");
        }
    }
    
    /**
     * 安全地获取当前用户ID
     * @return 用户ID，如果未登录则返回null
     */
    public Long getCurrentUserIdSafely() {
        User user = getCurrentUserSafely();
        return user != null ? user.getId() : null;
    }
    
    /**
     * 获取当前用户角色
     * @return 用户角色
     * @throws RuntimeException 如果未找到当前登录用户
     */
    public Role getCurrentUserRole() {
        return getCurrentUser().getRole();
    }
    
    /**
     * 检查当前用户是否是管理员
     * @return true如果当前用户是管理员
     */
    public boolean isAdmin() {
        User user = getCurrentUserSafely();
        return user != null && user.getRole() == Role.ADMIN;
    }
    
    /**
     * 检查当前用户是否是客服
     * @return true如果当前用户是客服
     */
    public boolean isAgent() {
        User user = getCurrentUserSafely();
        return user != null && user.getRole() == Role.AGENT;
    }
    
    /**
     * 检查当前用户是否是客户
     * @return true如果当前用户是客户
     */
    public boolean isCustomer() {
        User user = getCurrentUserSafely();
        return user != null && user.getRole() == Role.CUSTOMER;
    }
    
    /**
     * 检查当前用户是否是主管
     * @return true如果当前用户是主管
     */
    public boolean isSupervisor() {
        User user = getCurrentUserSafely();
        return user != null && user.getRole() == Role.SUPERVISOR;
    }
    
    /**
     * 检查当前用户是否已认证
     * @return true如果用户已登录
     */
    public boolean isAuthenticated() {
        return getCurrentUserSafely() != null;
    }
}

